# -*- coding: utf-8 -*-
import logging
import time
import thread
import json
import util

import poplib

import re
from email.parser import Parser
from email.header import decode_header
from bs4 import BeautifulSoup
from functools import reduce
import requests

logging.basicConfig(level=logging.INFO,
                        filename='./log.txt',
                        filemode='w',
                        format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')



def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset


def decode_str(s):
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value


def print_info(msg, indent=0, urls=list):
    # if indent == 0:
    #     for header in ['From', 'To', 'Subject']:
    #         value = msg.get(header, '')
    #         if value:
    #             if header=='Subject':
    #                 value = decode_str(value)
    #             else:
    #                 hdr, addr = parseaddr(value)
    #                 name = decode_str(hdr)
    #                 value = u'%s <%s>' % (name, addr)
    #         print('%s%s: %s' % ('  ' * indent, header, value))
    if (msg.is_multipart()):
        parts = msg.get_payload()
        for n, part in enumerate(parts):
            # print('%spart %s' % ('  ' * indent, n))
            # print('%s--------------------' % ('  ' * indent))
            print_info(part, indent + 1,urls=urls)
    else:
        content_type = msg.get_content_type()
        if content_type=='text/plain' or content_type=='text/html':
            content = msg.get_payload(decode=True)
            charset = guess_charset(msg)
            #encoding="utf-8"
            if charset:
                content = content.decode("utf-8")
            #print('%sText: %s' % ('  ' * indent, content + '...'))
            soup = BeautifulSoup(content, 'html.parser')
            # 找出所有的 a 标签， 因为所有的链接都在 a 标签内
            data = soup.find_all('a')
            if data:
                for item in data:
                    result = re.findall(".*href=\"(.*)\" style.*", str(item))
                    if result:
                        url_account = {"new_account": result[0]}
                        urls.append(url_account)
                    if item.string is not None and item['href'] != 'javascript:;' and item['href'] != '#':
                        steam_mail = {item.string: item.get('href')}
                        urls.append(steam_mail)


def login(email,authority_code,mail_server):
    try:
        print mail_server
        host = mail_server["mail_server"]
        port = mail_server["port"]
        SSL = mail_server["SSL"]
        if SSL == True:
            server = poplib.POP3_SSL(host=host, port=port)
        else:
            server = poplib.POP3(host=host, port=port)
        server.set_debuglevel(1)
        print(server.getwelcome())
        # 认证:
        server.user(email)
        server.pass_(authority_code)
        mail_total, total_size = server.stat()
        print('Messages: %s. Size: %s' % (mail_total, total_size))
        return server
    except Exception:
        return ""


def get_mail_activation_urls(server):
    try:
        resp, mails, octets = server.list()
        #获取最新一封邮件, 注意索引号从1开始:
        resp, lines, octets = server.retr(len(mails))
        # 解析邮件:
        msg = Parser().parsestr('\r\n'.join(lines))
        # 打印邮件内容:
        urls = list()
        print_info(msg, urls=urls)
        filter_function = lambda x, y: x if y in x else x + [y]
        urls = reduce(filter_function, [[], ] + urls)
        # 慎重:将直接从服务器删除邮件:
        # server.dele(len(mails))
        # 关闭连接:
        server.quit()
        return urls
    except Exception:
        return ""
    print mail_server
    host = mail_server["mail_server"]
    port = mail_server["port"]
    server = poplib.POP3(host=host, port=port)
    server.set_debuglevel(1)
    print(server.getwelcome())
    # 认证:
    server.user(email)
    server.pass_(authority_code)
    mail_total, total_size = server.stat()
    print('Messages: %s. Size: %s' % (mail_total, total_size))
    return server


def get_mail_activation_urls(server):
    resp, mails, octets = server.list()
    #获取最新一封邮件, 注意索引号从1开始:
    resp, lines, octets = server.retr(len(mails))
    # 解析邮件:
    msg = Parser().parsestr('\r\n'.join(lines))
    # 打印邮件内容:
    urls = list()
    print_info(msg, urls=urls)
    filter_function = lambda x, y: x if y in x else x + [y]
    urls = reduce(filter_function, [[], ] + urls)
    # 慎重:将直接从服务器删除邮件:
    # server.dele(len(mails))
    # 关闭连接:
    server.quit()
    return urls


def activation_account(*account):
    email = account[0]
    authority_code = account[1]
    mail_server = account[2]
    proxies = account[3]
    print "========================"+json.dumps(account)
    print account
    server = login(email,authority_code,mail_server)
    if not server:
        logging.info("account email  "+ "  log failed")
    mail_activation_urls = get_mail_activation_urls(server)
    if not mail_activation_urls:
        logging.info( "get account  " +email+"  activation_urls failed")
    for item in mail_activation_urls:
        for key in item:
            if key == "new_account":
                url = item[key]
                url = url.replace("&amp;", "&")
                creationid = url.split("&creationid=")
                creationid = creationid[1]
                logging.info("finally real activate url="+url+"    creationid=     "  +creationid )
                result = requests.get(url, proxies=proxies)
                #print "steam account activation result %s" %result.content
                if result.status_code == 200:
                    save_info_url = "https://store.steampowered.com/join/createaccount/"
                    accountname = util.GenUserName(10);
                    password =  util.GenPassword(12)
                    data={
                        "accountname": accountname,
                        "password":password,
                        "count":3,
                        "lt":0,
                        "creation_sessionid": creationid,
                        "embedded_appid":0
                    }
                    account_info = requests.post(save_info_url, data=data,proxies=proxies)
                    logging.info("response from steam "+ json.dumps(account_info.content))
                    if account_info.status_code==200:
                            result = account_info.content
                            result = json.loads(result)
                            if result:
                                if result.get("bSuccess") == True:
                                    with open("./activation_result.txt", 'a') as f:
                                        f.write(
                                            email + "  activation success  " + "  username=  " + accountname + "    password     " + password + "\n")
                                        f.close()
                                else:
                                    logging.info(
                                        email + "  activation failed  " + "  username=  " + accountname + "    password     " + password +"\n")








